package design_patterns_and_best_practices_in_java;

enum GeometryCalculatorBeanFactory {
    LOCAL {
        @Override
        public GeometryCalculatorBean makeGeometryCalculator() {
            return new GeometryBean();
        }
    },
    REMOTE_PROXY {
        @Override
        public GeometryCalculatorBean makeGeometryCalculator() {
            try {
                return new GeometryBeanProxy();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    };

    public abstract GeometryCalculatorBean makeGeometryCalculator();
}

interface GeometryCalculatorBean {
    double calcualteCircleCircumference(Circle circle);
}

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2019-11-14 下午3:31
 */
public class Chapter4Proxy {
    public static void main(String[] args) {
        GeometryCalculatorBean circle = GeometryCalculatorBeanFactory.REMOTE_PROXY.makeGeometryCalculator();
        System.out.printf("Circle diameter %f", circle.calcualteCircleCircumference(new Circle()));
    }
}

class Circle {
}

class GeometryBean implements GeometryCalculatorBean {

    @Override
    public double calcualteCircleCircumference(Circle circle) {
        return 0.1f;
    }
}

class GeometryBeanProxy implements GeometryCalculatorBean {

    private final GeometryCalculatorBean bean;

    public GeometryBeanProxy() throws Exception {
        bean = doJNDILookup("remote://localhost:4447", "user", "db.password");
    }

    private GeometryCalculatorBean doJNDILookup(final String urlProvider, final String securityPrincipal,
                                                final String securityCredentials) throws InterruptedException {
        System.out.println("Do JNDI lookup for bean");
        Thread.sleep(123);
        return GeometryCalculatorBeanFactory.LOCAL.makeGeometryCalculator();
    }

    @Override
    public double calcualteCircleCircumference(Circle circle) {
        return bean.calcualteCircleCircumference(circle);
    }
}
